#!/usr/bin/env python
import os
import django

# 设置Django环境
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'host_management.settings')
django.setup()

# 导入模型和工具
from hosts.models import City, Datacenter, Host
from hosts.utils import generate_password

def main():
    # 创建城市
    beijing, created = City.objects.get_or_create(name="北京", code="BJ")
    shanghai, created = City.objects.get_or_create(name="上海", code="SH")
    guangzhou, created = City.objects.get_or_create(name="广州", code="GZ")

    # 创建机房
    dc1, created = Datacenter.objects.get_or_create(
        name="北京亦庄机房",
        defaults={"code": "BJ-YZ", "city": beijing, "address": "北京市经济技术开发区"}
    )
    dc2, created = Datacenter.objects.get_or_create(
        name="北京海淀机房",
        defaults={"code": "BJ-HD", "city": beijing, "address": "北京市海淀区"}
    )
    dc3, created = Datacenter.objects.get_or_create(
        name="上海浦东机房",
        defaults={"code": "SH-PD", "city": shanghai, "address": "上海市浦东新区"}
    )
    dc4, created = Datacenter.objects.get_or_create(
        name="广州天河机房",
        defaults={"code": "GZ-TH", "city": guangzhou, "address": "广州市天河区"}
    )

    # 创建主机
    hosts_data = [
        {"hostname": "server-bj-01", "ip_address": "192.168.1.101", "datacenter": dc1, "cpu_cores": 4, "memory_gb": 8},
        {"hostname": "server-bj-02", "ip_address": "192.168.1.102", "datacenter": dc1, "cpu_cores": 8, "memory_gb": 16},
        {"hostname": "server-bj-03", "ip_address": "192.168.1.103", "datacenter": dc2, "cpu_cores": 4, "memory_gb": 8},
        {"hostname": "server-sh-01", "ip_address": "192.168.2.101", "datacenter": dc3, "cpu_cores": 16, "memory_gb": 32},
        {"hostname": "server-sh-02", "ip_address": "192.168.2.102", "datacenter": dc3, "cpu_cores": 8, "memory_gb": 16},
        {"hostname": "server-gz-01", "ip_address": "192.168.3.101", "datacenter": dc4, "cpu_cores": 4, "memory_gb": 8},
    ]

    for host_data in hosts_data:
        Host.objects.get_or_create(
            hostname=host_data["hostname"],
            defaults={
                "ip_address": host_data["ip_address"],
                "datacenter": host_data["datacenter"],
                "cpu_cores": host_data["cpu_cores"],
                "memory_gb": host_data["memory_gb"],
                "status": "online",
                "disk_gb": 100,
                "os_type": "CentOS 7",
                "root_password": generate_password()
            }
        )

    print("数据库初始化完成！")

if __name__ == "__main__":
    main()